#!/usr/bin/python3
# -*-coding:utf-8 -*-
"""
JSON进阶
类的json序列化和反序列化
可以直接序列化为json的有 dict list str  int/float True/Flase None
"""
import json


class Student(object):

    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score


def student2dict(stu):
    return {'name': stu.name, 'age': stu.age, 'score': stu.score}


def dict2student(d):
    return Student(d['name'], d['age'], d['score'])


def main():
    s = Student('wangnan', 30, 99)
    # print(json.dumps(s))    #发生异常: TypeError : Object of type Student is not JSON serializable
    d = student2dict(s)
    print(json.dumps(d))
    print(json.dumps(s, default=student2dict))
    print(dir(s))
    st = json.dumps(s, default=lambda obj: obj.__dict__)
    print(st)
    print(type(st))
    d = eval(st)
    print(type(d))
    print(d.keys())
    print(d.values())
    print(d)
    # st = '{"name": "wangnan", "age": 30, "score": 99}'
    print(json.loads(st, object_hook=dict2student))   # <__main__.Student object at 0x7f800996b2e0>


if __name__ == "__main__":
    main()
